package com.layer8apps;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: a873553
 * Date: 1/20/13
 * Time: 8:30 PM
 * To change this template use File | Settings | File Templates.
 */
public class MooDBSearch extends Activity {

    private String productUPC = "";
    private Product finalProduct;
    private String url = "http://www.moodb.net/search.asp";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.moosearch);
        productUPC = getIntent().getStringExtra("product");
        HttpTask httpTask = new HttpTask();
        httpTask.execute(url);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.moo_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_accept:
                saveResult();
                setResult(RESULT_OK);
                finish();
                return true;
            case R.id.menu_cancel:
                cancelResult();
                setResult(RESULT_CANCELED);
                finish();
                return true;
            default:
                return true;
        }
    }

    private void saveResult() {
        File from = new File(Environment.getExternalStorageDirectory() + "/MovieKeeper/temp.png");
        File to = new File(Environment.getExternalStorageDirectory() + "/MovieKeeper/" + productUPC + ".png");
        from.renameTo(to);
        DatabaseHandler db = new DatabaseHandler(this);
        db.addProduct(finalProduct);
    }

    private void cancelResult() {
        File sDir = new File(Environment.getExternalStorageDirectory() + "/MovieKeeper/temp.png");
        sDir.delete();
    }

    private class HttpTask extends AsyncTask<String, Void, Product> {

        @Override
        protected Product doInBackground(String... params) {
            String data;
            Product product = new Product();
            try {
                ConnectionManager conn = ConnectionManager.newConnection();
                List<NameValuePair> args = new LinkedList<NameValuePair>();
                args.add(new BasicNameValuePair("txtMainSearch", productUPC));
                args.add(new BasicNameValuePair("cboMainSearchType", "U"));
                args.add(new BasicNameValuePair("btnGo", "Go"));
                data = conn.postData(url, args);
                if (data != null) {
                    // Check for titles based on the UPC
                    if (data.contains("No Titles found")) {
                        return null;
                    } else {
                        data = parseID(data);
                    }
                    // Get the page for the movie based off the ID
                    if (data != null && data.length() > 0) {
                        data = conn.getData("http://www.moodb.net/movie.asp?id=" + data);
                    } else {
                        return null;
                    }
                    // Parse out the movie information
                    if (data != null) {
                        product = parseMovie(data);
                    } else {
                        return null;
                    }
                    if (product != null) {
                        product.setUpc(productUPC);
                    } else {
                        return null;
                    }
                }
            } catch (Exception e) {
            }
            return product;
        }

        @Override
        protected void onPostExecute(final Product product) {
            if (product != null) {
                TextView txtName = (TextView) findViewById(R.id.mooTitle);
                TextView txtTag = (TextView) findViewById(R.id.mooTagline);
                TextView txtIMDB = (TextView) findViewById(R.id.mooIMDB);
                ImageView imgMovie = (ImageView) findViewById(R.id.mooImage);
                txtName.setText(product.getName());
                txtTag.setText(product.getTag());
                txtIMDB.setText("See this movie on IMDB");
                txtIMDB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent browser = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.imdb.com/title/" + product.getImdb()));
                        startActivity(browser);
                    }
                });
                ConnectionManager cm = ConnectionManager.getInstance();
                Bitmap bmp = cm.getBitmap(product.getImageURL());
                try {
                    File sDir = new File(Environment.getExternalStorageDirectory() + "/MovieKeeper/");
                    sDir.mkdirs();
                    OutputStream stream = new FileOutputStream(sDir.getPath() + "/temp.png", false);
                    bmp.compress(Bitmap.CompressFormat.PNG, 80, stream);
                    stream.close();
                } catch (Exception e) {
                }
                imgMovie.setImageBitmap(bmp);
                finalProduct = product;
            }
        }

        private String parseID(String data) {
            data = data.substring(data.indexOf("movie.asp?id=") + 13);
            data = data.substring(0, data.indexOf("\">"));
            return data;
        }

        private Product parseMovie(String data) {
            Product product = new Product();
            try {
                // Begin parsing out any pictures that are available
                String tempData = data;
                tempData= tempData.substring(tempData.indexOf("Movie information"), tempData.indexOf("This movie is"));
                String img[] = tempData.split("<img");
                if (img.length > 0) {
                    for (int x = 1;x < img.length;x++) {
                        img[x] = "http://www.moodb.net/" + img[x].substring(6, img[x].indexOf("alt") - 2);
                    }
                    product.setImageURL(img[1]);
                }

                // Parse out movie title
                tempData = data.substring(data.indexOf("Movie title"));
                tempData = tempData.substring(tempData.indexOf("<b>"), tempData.indexOf("</b>"));
                tempData = tempData.replace("\n", "");
                tempData = tempData.substring(3);
                product.setName(tempData);

                // Parse MOODb ID
                tempData = data.substring(data.indexOf("MOODb ID"));
                tempData = tempData.substring(tempData.indexOf("<font"));
                tempData = tempData.substring(tempData.indexOf(">"));
                tempData = tempData.substring(1, tempData.indexOf("</font>"));
                product.setMid(tempData);

                // Parse IMDB ID
                tempData = data.substring(data.indexOf("IMDb ID"));
                tempData = tempData.substring(tempData.indexOf("<a href"));
                tempData = tempData.substring(tempData.indexOf(">"));
                tempData = tempData.substring(1, tempData.indexOf("</a>"));
                product.setImdb(tempData);

                // Parse tagline
                tempData = data.substring(data.indexOf("Tagline"));
                tempData = tempData.substring(tempData.indexOf("<font"));
                tempData = tempData.substring(tempData.indexOf(">"));
                tempData = tempData.substring(1, tempData.indexOf("<br>"));
                tempData = tempData.replace("\n","");
                product.setTag(tempData);

                product.setImage(productUPC + ".png");
            } catch (Exception e) {
                return null;
            }
            return product;
        }
    }
}
